package com.drinkdelivery.front.service;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONObject;
import com.drinkdelivery.common.exception.base.BaseException;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

@Service
public class WxService {

//    @Value("${wx.appId}")
//    private String appId;
//
//    @Value("${wx.appSecret}")
//    private String appSecret;

    private String appId = "wxc3f9bddb87b16963";
    private String appSecret = "3c9c9871105cc268a14bf44ba6b8c606";

    private static final String WX_SESSION_URL = "https://api.weixin.qq.com/sns/jscode2session";

    public String getOpenIdFromCode(String code) {
        JSONObject sessionData = getSessionData(code);
        return sessionData.getStr("openid");
    }

    public String getSessionKeyFromCode(String code) {
        JSONObject sessionData = getSessionData(code);
        return sessionData.getStr("session_key");
    }

    private JSONObject getSessionData(String code) {
        RestTemplate restTemplate = new RestTemplate();
        String url = WX_SESSION_URL + "?appid=" + appId + "&secret=" + appSecret + "&js_code=" + code + "&grant_type=authorization_code";
        ResponseEntity<String> response = restTemplate.getForEntity(url, String.class);

        JSONObject data = new JSONObject(response.getBody());

        if (ObjectUtil.isNull(data)) {
            throw new BaseException("微信平台接口异常，没任何数据返回！");
        }
        if (data.containsKey("errcode") && !data.getStr("errcode").equals("0")) {
            if (data.containsKey("errmsg")) {
                // 保存到微信异常表
//                wxExceptionDispose(data, "微信小程序登录凭证校验异常");
                throw new BaseException("微信接口调用失败：" + data.getStr("errcode") + data.getStr("errmsg"));
            }
        }

        return data;
    }
}
